package com.xuanwei.core.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.xuanwei.core.entity.RoleVo;
import com.xuanwei.core.exception.XwException;
import com.xuanwei.core.service.IXwManagementPermissionService;
import com.xuanwei.core.service.IXwManagementRolePermissionService;
import com.xuanwei.core.service.IXwManagementRoleService;
import com.xuanwei.dao.entity.XwManagementPermission;
import com.xuanwei.dao.entity.XwManagementRole;
import com.xuanwei.dao.entity.XwManagementRolePermission;
import com.xuanwei.dao.mapper.XwManagementRoleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author mjy
 * @since 2019-04-14
 */
@Service
public class XwManagementRoleServiceImpl extends ServiceImpl<XwManagementRoleMapper, XwManagementRole> implements IXwManagementRoleService {

    @Autowired
    private IXwManagementRolePermissionService rolePermissionService;

    @Autowired
    private IXwManagementPermissionService permissionService;

    @Override
    public XwManagementRole findPermissionByUserId(Integer id) {
        return baseMapper.selectAllPermission(id);
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void add(String name, Integer[] ids) {
        XwManagementRole managementRole = getBaseMapper().selectOne(new QueryWrapper<XwManagementRole>().select("id,`name`").eq("`name`", name));
        if (managementRole != null) {
            throw new XwException("已存在该角色名");
        }
        XwManagementRole role = new XwManagementRole();
        role.setName(name);
        role.setCreateTime(LocalDateTime.now());
        role.setUpdateTime(LocalDateTime.now());
        //保留角色值
        role.setValue("XX");
        getBaseMapper().insert(role);
        Integer roleId = role.getId();

        for (Integer id : ids) {
            XwManagementRolePermission rolePermission = new XwManagementRolePermission();
            rolePermission.setRoleId(roleId);
            rolePermission.setPermissionId(id);
            rolePermissionService.getBaseMapper().insert(rolePermission);
        }
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void update(Integer id, String name, Integer[] ids) {
        XwManagementRole managementRole = getBaseMapper().selectById(id);
        if (managementRole == null) {
            throw new XwException("不存在该数据");
        }
        if (!managementRole.getId().equals(id) && managementRole.getName().equals(name)) {
            throw new XwException("已存在该角色名");
        }
        XwManagementRole role = new XwManagementRole();
        role.setId(managementRole.getId());
        role.setName(name);
        role.setUpdateTime(LocalDateTime.now());
        getBaseMapper().updateById(role);
        List<XwManagementRolePermission> managementRolePermissions = rolePermissionService.getBaseMapper().selectList(new QueryWrapper<XwManagementRolePermission>()
                .select("id").eq("role_id", role.getId()));
        managementRolePermissions.forEach(s ->
                rolePermissionService.getBaseMapper().deleteById(s.getId())
        );
        for (Integer _id : ids) {
            XwManagementRolePermission rolePermission = new XwManagementRolePermission();
            rolePermission.setRoleId(role.getId());
            rolePermission.setPermissionId(_id);
            rolePermissionService.getBaseMapper().insert(rolePermission);
        }
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void delete(Integer id) {
        XwManagementRole managementRole = getBaseMapper().selectById(id);
        if (managementRole == null) {
            throw new XwException("不存在该数据");
        }
        getBaseMapper().deleteById(id);
        List<XwManagementRolePermission> managementRolePermissions = rolePermissionService.getBaseMapper().selectList(new QueryWrapper<XwManagementRolePermission>()
                .select("id").eq("role_id", id));
        managementRolePermissions.forEach(s ->
                rolePermissionService.getBaseMapper().deleteById(s.getId())
        );

    }

    @Override
    public void list(Page<XwManagementRole> page) {

        getBaseMapper().selectPage(page,
                new QueryWrapper<XwManagementRole>().select("id,`name`,create_time").orderByDesc("update_time"));
    }

    @Override
    public RoleVo detail(Integer id) {
        XwManagementRole managementRole = getBaseMapper().selectById(id);
        if (managementRole == null) {
            throw new XwException("不存在该数据");
        }
        List<XwManagementRolePermission> managementRolePermissions = rolePermissionService.getBaseMapper().selectList(new QueryWrapper<XwManagementRolePermission>()
                .select("id,permission_id").eq("role_id", id));
        RoleVo roleVO = new RoleVo();
        roleVO.setId(managementRole.getId());
        roleVO.setName(managementRole.getName());
        ArrayList<RoleVo.RolePermission> permissions = Lists.newArrayListWithCapacity(managementRolePermissions.size());
        managementRolePermissions.forEach(s -> {
            XwManagementPermission p = permissionService.getBaseMapper().selectOne(
                    new QueryWrapper<XwManagementPermission>().select("id,`name`").eq("id", s.getPermissionId()));
            RoleVo.RolePermission permission = new RoleVo().new RolePermission();
            permission.setId(p.getId());
            permission.setName(p.getName());
            permissions.add(permission);
        });
        roleVO.setRolePermissions(permissions);
        return roleVO;
    }

    @Override
    public List<XwManagementPermission> permissionList() {
        return permissionService.getBaseMapper()
                .selectList(new QueryWrapper<XwManagementPermission>().select("id,`name`"));


    }

    @Override
    public List<XwManagementRole> roleList() {
        return getBaseMapper()
                .selectList(new QueryWrapper<XwManagementRole>().select("id,`name`,create_time"));

    }
}
